﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using OpenNETCF.Ftp;
using PDAMain.DAL;
using PDAMain.Entity;
using PDAMain.Interface;
using PDAMain.Forms.RepairWork;
using PDAMain.Forms.ReadingWatermeter;
using PDAMain.Forms.InspectionWork;
using PDAMain.Forms.CustomerWork;
using PDAMain.Forms.ApplyToRepair;
using PDAMain.Forms.ReadingAmmeter;


namespace PDAMain
{
    public partial class FuntionView : Form
    {
        public FuntionView()
        {
            InitializeComponent();
        }
        delegate void StringDelegate(string value);
        private FTP m_ftp;
        string[] UploadData = null;
        private bool UploadClick = true;
        private string CheckConnect = "";
        private string SuccessStr = "Transfer complete.";
        private int count = 0;
        private void GetUserRole()
        {
            string RoleCode = Identity.RoleCode;
            string[] ArrRole = RoleCode.Split(',');
            UploadData = ArrRole;
            foreach (string strRole in ArrRole)
            {

                //维修工单
                if (strRole.ToUpper() == "ROLE_REPAIRER")
                {
                    pictureBoxRepair.Visible = true;
                    lblRepairNum.Visible = true;
                    pictureBoxRepair_v2.Visible = false;
                }

                //巡检管理
                if (strRole.ToUpper() == "ROLE_INSPECTOR")
                {
                    pictureBoxInspection.Visible = true;
                    lblInpectionNum.Visible = true;
                    pictureBoxInspection_v2.Visible = false;
                }
                //客服工单
                if (strRole.ToUpper() == "ROLE_CUSTOM_SERVICE")
                {
                    pictureBoxCustomer.Visible = true;
                    lblCustomerNum.Visible = true;
                    pictureBoxCustomer_v2.Visible = false;
                }

                //电表抄表
                if (strRole.ToUpper() == "ROLE_AM_READING")
                {
                    pictureBoxAm.Visible = true;
                    lblAmNum.Visible = true;
                    pictureBoxAm_v2.Visible = false;
                }

                //水表抄表
                if (strRole.ToUpper() == "ROLE_WATER_READING")
                {
                    pictureBoxWater.Visible = true;
                    lblWaterNum.Visible = true;
                    pictureBoxWater_v2.Visible = false;
                }

                //系统设置
                if (strRole.ToUpper() == "ROLE_SUPER")
                {
                   
                    pictureBoxWater.Visible = true;
                    pictureBoxAm.Visible = true; 
                    pictureBoxRepair.Visible = true;
                    pictureBoxCustomer.Visible = true;
                    pictureBoxInspection.Visible = true;
                    pictureBoxSysConfig.Visible = true;
                    pictureBoxSysUpdate.Visible = true;

                    pictureBoxRepair_v2.Visible = false;
                    pictureBoxInspection_v2.Visible = false;
                    pictureBoxCustomer_v2.Visible = false;
                    pictureBoxAm_v2.Visible = false;
                    pictureBoxWater_v2.Visible = false;
                    pictureBoxSysConfig_v2.Visible = false;
                    pictureBoxSysUpdate_v2.Visible = false;


                    lblInpectionNum.Visible = true;
                    lblCustomerNum.Visible = true;
                    lblWaterNum.Visible = true;
                    lblAmNum.Visible = true;
                    lblRepairNum.Visible = true;

                }
            }
        }
        /// <summary>
        /// 跳转客服工单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBoxCustomer_Click(object sender, EventArgs e)
        {
            if (UploadClick)
            {
                Cursor.Current = Cursors.WaitCursor;
                Cursor.Show();
                CustomerList list = new CustomerList();
                list.Show();
                this.Close();
                Cursor.Current = Cursors.Default;
                Cursor.Hide();
            }
        }
        /// <summary>
        /// 跳转巡检工单页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBoxInspection_Click(object sender, EventArgs e)
        {
            if (UploadClick)
            {
                Cursor.Current = Cursors.WaitCursor;
                Cursor.Show();
                InspectionList list = new InspectionList();
                list.Show();
                this.Close();
                Cursor.Current = Cursors.Default;
                Cursor.Hide();
            }
        }
        /// <summary>
        /// 跳转维修工单页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBoxRepair_Click(object sender, EventArgs e)
        {
            if (UploadClick)
            {
                Cursor.Current = Cursors.WaitCursor;
                Cursor.Show();
                RepairWorkList list = new RepairWorkList();
                list.Show();
                this.Close();
                Cursor.Current = Cursors.Default;
                Cursor.Hide();
            }
        }
        /// <summary>
        /// 跳转抄电表页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBoxAm_Click(object sender, EventArgs e)
        {
            if (UploadClick)
            {
                Cursor.Current = Cursors.WaitCursor;
                Cursor.Show();
                //AmmeterReadingList ARL = new AmmeterReadingList();
                AmPlanList ARL = new AmPlanList();
                ARL.Show();
                this.Close();
                Cursor.Current = Cursors.Default;
                Cursor.Hide();
            }
        }
        /// <summary>
        /// 跳转抄水表页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBoxWater_Click(object sender, EventArgs e)
        {
            if (UploadClick)
            {
                Cursor.Current = Cursors.WaitCursor;
                Cursor.Show();
                //WaterReadingList WRL = new WaterReadingList();
                WaterPlanList WRL = new WaterPlanList();
                WRL.Show();
                this.Close();
                Cursor.Current = Cursors.Default;
                Cursor.Hide();
            }
        }
        /// <summary>
        /// 跳转修改密码页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBoxModifyPassword_Click(object sender, EventArgs e)
        {
            if (UploadClick)
            {
                Cursor.Current = Cursors.WaitCursor;
                Cursor.Show();
                ModifyPassword showForm = new ModifyPassword();
                showForm.Show();
                this.Close();
                Cursor.Current = Cursors.Default;
                Cursor.Hide();
            }
        }
        /// <summary>
        /// 跳转申请报修
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBoxApplyRepair_Click(object sender, EventArgs e)
        {
            if (UploadClick)
            {
                Cursor.Current = Cursors.WaitCursor;
                Cursor.Show();
                ApplyToRepair formShow = new ApplyToRepair();
                formShow.Show();
                this.Close();
                Cursor.Current = Cursors.Default;
                Cursor.Hide();
            }
        }
        /// <summary>
        /// 跳转系统配置页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBoxSysConfig_Click(object sender, EventArgs e)
        {
            if (UploadClick)
            {
                Cursor.Current = Cursors.WaitCursor;
                Cursor.Show();
                Config showForm = new Config();
                showForm.Show();
                this.Close();
                Cursor.Current = Cursors.Default;
                Cursor.Hide();
            }
        }
        /// <summary>
        /// 跳转系统升级页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBoxSystemUpdate_Click(object sender, EventArgs e)
        {
            MessageBox.Show("该版本已经是最新版本，无需再升级！");
        }
        /*private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                DataHelper.SynchronizationDataDao.UploadData();
                foreach (string strRole in UploadData)
                {
                    //维修工单
                    if (strRole.ToUpper() == "ROLE_REPAIRER")
                    {
                        DataHelper.RepairWorkDao.download();
                    }

                    //巡检管理
                    if (strRole.ToUpper() == "ROLE_INSPECTOR")
                    {
                        DataHelper.InspectionWorkDao.updateDataFromWebservice();
                    }
                    //客服工单
                    if (strRole.ToUpper() == "ROLE_CUSTOM_SERVICE")
                    {
                        DataHelper.CustomerWorkDao.updateDataFromWebservice();
                    }

                    //电表抄表
                    if (strRole.ToUpper() == "ROLE_AM_READING")
                    {
                        DataHelper.ReadingAmmeterDao.download();
                    }

                    //水表抄表
                    if (strRole.ToUpper() == "ROLE_WATER_READING")
                    {
                        DataHelper.ReadingWatermeterDao.download();
                    }

                    //系统设置
                    if (strRole.ToUpper() == "ROLE_SUPER")
                    {
                        DataHelper.InspectionWorkDao.updateDataFromWebservice();
                        DataHelper.CustomerWorkDao.updateDataFromWebservice();
                        DataHelper.RepairWorkDao.download();
                        DataHelper.ReadingAmmeterDao.download();
                        DataHelper.ReadingWatermeterDao.download();
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }*/
        void m_ftp_Connected(FTP source)
        {
            OnResponse("Connected.");
            CheckConnect = "";
            ConnectThread();
        }

        void m_ftp_ResponseReceived(FTP source, FTPResponse Response)
        {
            OnResponse(Response.Text);
        }

        private void OnResponse(string response)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new StringDelegate(OnResponse), new object[] { response });
                return;
            }
            if (response == CheckConnect && CheckConnect != "")
            {
                Cursor.Current = Cursors.Default;
                Cursor.Hide();
                UploadClick = true;
                MessageBox.Show("连接图片服务器失败，请重新设置");
                return;
            }
            if (response == SuccessStr)
            {
                progressBar1.Value++;
            }
            if (progressBar1.Value == progressBar1.Maximum)
            {
                Cursor.Current = Cursors.Default;
                Cursor.Hide();
                UploadClick = true;
                MessageBox.Show("上传成功！");
                progressBar1.Visible = false;
            }
        }

        private void ConnectServer()
        {
            OnResponse("Connecting");
            string IP = ConfigHelper.GetConfigValue("PicUrl");
            string Port = ConfigHelper.GetConfigValue("Port");
            string User = ConfigHelper.GetConfigValue("User");
            string Pwd = ConfigHelper.GetConfigValue("Pwd");
            CheckConnect = "User " + User + " cannot log in.";
            m_ftp = new FTP(IP);
            m_ftp.Port = int.Parse(Port);
            m_ftp.ConnectionTimeout = 5000;
            m_ftp.ResponseReceived += new FTPResponseHandler(m_ftp_ResponseReceived);
            m_ftp.Connected += new FTPConnectedHandler(m_ftp_Connected);
            m_ftp.BeginConnect(GetXmlString(User), GetXmlString(Pwd));
        }

        //处理XML中的特殊定义符
        private string GetXmlString(string value)
        {
            return value.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&").Replace("&apos;", "'").Replace("&quot;", "\"");
        }

        private void ConnectThread()
        {
            FTPFiles files = m_ftp.EnumFiles();
            DirectoryInfo Folder = new DirectoryInfo(TakePicture.imagePath);
            foreach (DirectoryInfo NextFolder in Folder.GetDirectories())
            {
                bool Is_CreateDirectory = true;
                if (files != null)
                {
                    foreach (FTPFile file in files)
                    {
                        if (NextFolder.Name == file.Name)
                        {
                            Is_CreateDirectory = false;
                            break;
                        }
                    }
                }
                if (Is_CreateDirectory)
                {
                    m_ftp.CreateDirectory(NextFolder.Name);
                }
                foreach (FileInfo NextFile in NextFolder.GetFiles())
                {
                    FileStream stream = File.OpenRead(NextFile.FullName);
                    m_ftp.SendFile(stream, NextFile.Name, NextFolder.Name);
                    stream.Close();
                    File.Delete(NextFile.FullName);
                }
            }
        }

       /* private void FuntionView_Closed(object sender, EventArgs e)
        {
            if (UploadClick)
            {
                //timer1.Enabled = false;
            }
        }*/

        private void FuntionView_Load(object sender, EventArgs e)
        {
            GetUserRole();
            messageCenter();
           
        }
        private void messageCenter()
        {
            Identity.AmNum = DataHelper.ReadingAmmeterDao.dataNum();
            lblAmNum.Text = Identity.AmNum;
            if (lblAmNum.Text == "0")
            {
                lblAmNum.Visible = false;
            }
            Identity.WaterNum = DataHelper.ReadingWatermeterDao.dataNum();
            lblWaterNum.Text = Identity.WaterNum;
            if (lblWaterNum.Text == "0")
            {
                lblWaterNum.Visible = false;
            }
            Identity.RepairNum = DataHelper.RepairWorkDao.dataNum();
            lblRepairNum.Text = Identity.RepairNum;
            if (lblRepairNum.Text == "0")
            {
                lblRepairNum.Visible = false;
            }
            Identity.CustomerNum = DataHelper.CustomerWorkDao.dataNum();
            lblCustomerNum.Text = Identity.CustomerNum;
            if (lblCustomerNum.Text == "0")
            {
                lblCustomerNum.Visible = false;
            }
            Identity.InspectionNum = DataHelper.InspectionWorkDao.dataNum();
            lblInpectionNum.Text = Identity.InspectionNum;
            if (lblInpectionNum.Text == "0")
            {
                lblInpectionNum.Visible = false;
            }
        }

        private void menuUpload_Click(object sender, EventArgs e)
        {
            if (NetWorkState.checkWifiState())
            {
                DirectoryInfo Folder = new DirectoryInfo(TakePicture.imagePath);
                try
                {
                    DirectoryInfo[] dir = Folder.GetDirectories();
                    if (dir.Length > 0)
                    {
                        //统计需上传的图片个数
                        foreach (DirectoryInfo NextFolder in dir)
                        {
                            count += NextFolder.GetFiles().Length;
                        }
                    }
                }
                catch { }
                if (count > 0)
                {
                    if (MessageBox.Show("确定需要上传图片吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        try
                        {
                            GPRS gprs = new GPRS();
                            if (gprs.GPRS_Status() != "Disconnected")
                            {
                                gprs.ConnGPRS(false);
                            }
                            Cursor.Current = Cursors.WaitCursor;
                            Cursor.Show();
                            UploadClick = false;
                            progressBar1.Visible = true;
                            progressBar1.Maximum = count;
                            progressBar1.Value = 0;
                            ConnectServer();
                        }
                        catch
                        {
                            if (!NetWorkState.checkGprsState())
                            {
                                MessageBox.Show("Wifi网络已断开");
                                UploadClick = true;
                            }
                            else
                            {
                                MessageBox.Show("上传异常，请重试");
                                UploadClick = true;
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("没有图片需要上传");
                }
            }
            else
            {
                MessageBox.Show("无法连接到Wifi网络");
            }
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            if (UploadClick)
            {
                if (MessageBox.Show("确定要退出系统吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    DLL.Shutdown();
                    Application.Exit();
                }
            }
        }
    }
}